<template>
	<view class="container">
		<!-- 骨架屏 -->
		<view v-if="loading" class="skeleton">
			<view class="skeleton-header"></view>
			<view class="skeleton-content">
				<view class="skeleton-line" v-for="i in 5" :key="i"></view>
			</view>
		</view>

		<!-- 详情内容 -->
		<view v-else class="detail-container">
			<!-- 订单状态 -->
			<view class="status-container" :class="getStatusClass(orderDetail.status)">
				<view class="status-text">{{ getStatusText(orderDetail.status) }}</view>
			</view>

			<!-- 订单信息 -->
			<view class="info-card">
				<view class="card-title">报修信息</view>
				<view class="info-item">
					<text class="item-label">报修编号：</text>
					<text class="item-value">{{ orderDetail.id }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">报修时间：</text>
					<text class="item-value">{{ formatDate(orderDetail.createTime) }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">联系人：</text>
					<text class="item-value">{{ orderDetail.contactName }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">联系电话：</text>
					<text class="item-value">{{ orderDetail.contactPhone }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">维修地址：</text>
					<text class="item-value">{{ orderDetail.location }}</text>
				</view>
				<view class="info-item">
					<text class="item-label">报修内容：</text>
					<text class="item-value">{{ orderDetail.content }}</text>
				</view>
			</view>

			<!-- 维修信息 -->
			<view class="info-card" v-if="orderDetail.status >= 1">
				<view class="card-title">维修信息</view>
				<view class="info-item" v-if="orderDetail.assignTime">
					<text class="item-label">分配时间：</text>
					<text class="item-value">{{ formatDate(orderDetail.assignTime) }}</text>
				</view>
				<view class="info-item" v-if="orderDetail.startTime">
					<text class="item-label">开始维修：</text>
					<text class="item-value">{{ formatDate(orderDetail.startTime) }}</text>
				</view>
				<view class="info-item" v-if="orderDetail.finishTime">
					<text class="item-label">完成时间：</text>
					<text class="item-value">{{ formatDate(orderDetail.finishTime) }}</text>
				</view>
				<view class="info-item" v-if="orderDetail.feedback">
					<text class="item-label">维修反馈：</text>
					<text class="item-value">{{ orderDetail.feedback }}</text>
				</view>
			</view>

			<!-- 评价信息（已评价） -->
			<view class="info-card" v-if="evaluation && evaluation.id">
				<view class="card-title">评价信息</view>
				<view class="evaluation-header">
					<view class="rating">
						<uni-icons v-for="i in 5" :key="i" :type="i <= evaluation.score ? 'star-filled' : 'star'"
							size="24" :color="i <= evaluation.score ? '#FFD700' : '#CCCCCC'"></uni-icons>
						<text class="score-text">{{ evaluation.score }}分</text>
						<text class="rating-desc">({{ getRatingDesc(evaluation.score) }})</text>
					</view>
					<view class="evaluation-time" v-if="evaluation.createTime">
						{{ formatDate(evaluation.createTime) }}
					</view>
				</view>
				<view class="evaluation-content" v-if="evaluation.content">
					{{ evaluation.content }}
				</view>
				<view class="no-content" v-if="!evaluation.content">
					用户未填写评价内容
				</view>
			</view>

			<!-- 操作按钮（维修人员） -->
			<view class="action-container" v-if="isRepairer">
				<button class="btn btn-primary" v-if="orderDetail.status === 0" @click="handleAccept">接单</button>
				<button class="btn btn-primary" v-if="orderDetail.status === 1" @click="handleComplete">完成维修</button>
			</view>

			<!-- 操作按钮（学生/普通用户） -->
			<view class="action-container" v-else>
				<!-- 未评价 & 已完成 才显示评价按钮 -->
				<button class="btn btn-primary evaluate-btn" v-if="orderDetail.status === 2 && !evaluation"
					@click="showEvaluationForm = true">
					评价维修
				</button>
			</view>

			<!-- 底部留白 -->
			<view style="height: 120rpx;"></view>
		</view>

		<!-- 评价弹窗 -->
		<uni-popup ref="evaluationPopup" type="bottom" @change="popupChange">
			<view class="evaluation-form" v-if="showEvaluationForm">
				<view class="form-header">
					<text class="form-title">评价维修服务</text>
					<text class="close-btn" @click="showEvaluationForm = false">×</text>
				</view>

				<view class="form-content">
					<view class="evaluation-tips">您的评价对我们很重要，感谢您的反馈！</view>

					<view class="rating-container">
						<text class="rating-title">服务评分</text>
						<view class="stars">
							<uni-icons v-for="i in 5" :key="i"
								:type="i <= evaluationForm.score ? 'star-filled' : 'star'" size="30"
								:color="i <= evaluationForm.score ? '#FFD700' : '#CCCCCC'"
								@click="evaluationForm.score = i"></uni-icons>
							<text class="score-text">{{ evaluationForm.score }}分</text>
						</view>
						<text class="rating-desc">{{ getRatingDesc(evaluationForm.score) }}</text>
					</view>

					<view class="comment-container">
						<text class="comment-title">评价内容</text>
						<textarea class="comment-input" v-model="evaluationForm.content"
							placeholder="请输入您对维修服务的评价，如服务态度、专业程度、响应速度等（选填）" maxlength="200"></textarea>
						<text class="comment-count">{{ evaluationForm.content.length }}/200</text>
					</view>
				</view>

				<view class="form-footer">
					<button class="btn btn-cancel" @click="showEvaluationForm = false">取消</button>
					<button class="btn btn-submit" @click="submitEvaluation">提交评价</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		http
	} from '@/utils/request.js'
	import {
		checkIsRepairer
	} from '@/utils/auth.js'

	export default {
		data() {
			return {
				id: null, // 工单ID
				loading: true,
				orderDetail: {},
				isRepairer: false,
				evaluation: null, // 评价信息
				showEvaluationForm: false,
				evaluationForm: {
					score: 5,
					content: ''
				}
			}
		},
		onLoad(options) {
			// 初始化获取工单ID
			if (options.id) {
				this.id = options.id
				this.loadOrderDetail() // 加载工单详情

				// 如果有evaluate参数且值为true，自动显示评价表单
				if (options.evaluate === 'true') {
					// 加载数据后显示评价表单
					setTimeout(() => {
						this.showEvaluationForm = true
						// 显示弹窗
						this.$nextTick(() => {
							this.$refs.evaluationPopup.open()
						})
					}, 1000) // 延迟一秒，等待数据加载完成
				}
			} else {
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}

			// 检查用户角色
			this.isRepairer = checkIsRepairer()
		},
		methods: {
			// 获取工单详情数据
			async loadOrderDetail() {
				this.loading = true
				try {
					// 使用新添加的API获取工单详情
					const apiUrl = this.isRepairer ? '/api/task/getRootInfoDetail' : '/api/repairNotice/getDetailInfo'
					const res = await http.get(apiUrl, {
						id: this.id
					})

					console.log('工单详情API响应:', res)

					if (res.code === 0 && res.data) {
						this.orderDetail = res.data
						console.log('解析后的工单详情:', this.orderDetail)

						// 处理图片数据，如果图片字段是逗号分隔的字符串，转换为数组
						if (this.orderDetail.images && typeof this.orderDetail.images === 'string') {
							this.orderDetail.images = this.orderDetail.images.split(',').filter(img => img);
						}

						// 查询评价状态
						await this.checkEvaluationStatus()
					} else {
						uni.showToast({
							title: res.msg || '获取数据失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取工单详情失败:', error)
					uni.showToast({
						title: '暂时不支持该功能',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 检查评价状态并加载评价信息
			async checkEvaluationStatus() {
				try {
					// 只有已完成的工单才需要检查评价状态
					if (this.orderDetail.status !== 2) return

					// 查询是否已评价
					const evalStatusRes = await http.get('/api/evaluation/isEvaluated', {
						repairId: this.id
					})
					console.log('评价状态查询结果:', evalStatusRes)

					// 如果已评价，加载评价详情
					if (evalStatusRes.code === 0 && evalStatusRes.data === true) {
						await this.loadEvaluation()
					}
				} catch (error) {
					console.error('检查评价状态失败:', error)
				}
			},

			// 加载评价信息
			async loadEvaluation() {
				try {
					// 调用获取评价信息的接口
					const res = await http.get('/api/evaluation/info', {
						repairId: this.id
					})
					console.log('评价接口返回:', res)
					if (res.code === 0) {
						this.evaluation = res.data || null
						console.log('评价信息:', this.evaluation)
					} else {
						console.error('评价信息获取失败:', res.msg)
					}
				} catch (error) {
					console.error('获取评价信息失败:', error)
				}
			},

			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return ''
				const date = new Date(dateString)
				if (isNaN(date.getTime())) return dateString

				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')

				return `${year}-${month}-${day} ${hours}:${minutes}`
			},

			// 获取状态文字
			getStatusText(status) {
				const statusMap = {
					0: '待处理',
					1: '维修中',
					2: '已完成'
				}
				return statusMap[status] !== undefined ? statusMap[status] : '未知状态'
			},

			// 获取状态对应的CSS类
			getStatusClass(status) {
				const classMap = {
					0: 'status-pending',
					1: 'status-processing',
					2: 'status-completed'
				}
				return classMap[status] || 'status-unknown'
			},

			// 处理接单
			async handleAccept() {
				uni.showLoading({
					title: '正在接单...'
				})
				try {
					const res = await http.post(`/api/task/updateTaskStart?id=${this.id}`)
					if (res.code === 0) {
						uni.showToast({
							title: '接单成功',
							icon: 'success'
						})
						// 刷新详情
						this.loadOrderDetail()
					} else {
						uni.showToast({
							title: res.msg || '接单失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('接单异常:', error)
					uni.showToast({
						title: '接单操作失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 处理完成维修
			async handleComplete() {
				uni.showLoading({
					title: '正在提交...'
				})
				try {
					const res = await http.post(`/api/task/updataTaskFinish?id=${this.id}`)
					if (res.code === 0) {
						uni.showToast({
							title: '操作成功',
							icon: 'success'
						})
						// 刷新详情
						this.loadOrderDetail()
					} else {
						uni.showToast({
							title: res.msg || '操作失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('完成维修异常:', error)
					uni.showToast({
						title: '完成操作失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 弹窗状态变化
			popupChange(e) {
				if (!e.show) {
					this.showEvaluationForm = false
				}
			},

			// 提交评价
			async submitEvaluation() {
				if (this.evaluationForm.score < 1 || this.evaluationForm.score > 5) {
					uni.showToast({
						title: '请选择1-5星评分',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '提交中...'
				})
				try {
					const data = {
						repairId: this.id,
						score: this.evaluationForm.score,
						content: this.evaluationForm.content
					}

					console.log('提交的评价数据:', data)

					const res = await http.post('/api/evaluation/add', data)
					console.log('评价提交结果:', res)

					if (res.code === 0) {
						uni.showToast({
							title: '评价成功',
							icon: 'success'
						})
						// 关闭弹窗
						this.showEvaluationForm = false

						// 刷新评价信息
						setTimeout(() => {
							this.loadEvaluation()

							// 通知列表页刷新评价状态
							// 获取上一页实例，确保整个应用的数据一致性
							const pages = getCurrentPages()
							if (pages.length > 1) {
								const prevPage = pages[pages.length - 2]
								// 如果上一页是订单列表页
								if (prevPage.route && prevPage.route.includes('order/index')) {
									// 更新订单列表中的评价状态
									const orderList = prevPage.orderList
									if (orderList && Array.isArray(orderList)) {
										const targetOrder = orderList.find(item => item.id === this.id)
										if (targetOrder) {
											targetOrder.evaluated = true
										}
									}
								}
							}
						}, 500)
					} else {
						uni.showToast({
							title: res.msg || '评价失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('提交评价失败:', error)
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 获取评分描述
			getRatingDesc(score) {
				const descMap = {
					1: '非常不满意',
					2: '不满意',
					3: '一般',
					4: '满意',
					5: '非常满意'
				}
				return descMap[score] || ''
			}
		}
	}
</script>

<style>
	.container {
		padding-bottom: 40rpx;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 骨架屏样式 */
	.skeleton {
		padding: 20rpx;
	}

	.skeleton-header {
		height: 100rpx;
		background-color: #e0e0e0;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
	}

	.skeleton-content {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 8rpx;
	}

	.skeleton-line {
		height: 30rpx;
		background-color: #e0e0e0;
		border-radius: 4rpx;
		margin-bottom: 20rpx;
	}

	/* 状态样式 */
	.status-container {
		height: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.status-text {
		font-size: 36rpx;
		font-weight: bold;
		color: #fff;
	}

	.status-pending {
		background-color: #faad14;
	}

	.status-processing {
		background-color: #1890ff;
	}

	.status-completed {
		background-color: #52c41a;
	}

	.status-unknown {
		background-color: #bfbfbf;
	}

	/* 卡片样式 */
	.info-card {
		background-color: #fff;
		border-radius: 8rpx;
		margin: 20rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #333;
		position: relative;
		padding-left: 20rpx;
	}

	.card-title::before {
		content: '';
		position: absolute;
		left: 0;
		top: 8rpx;
		width: 8rpx;
		height: 24rpx;
		background-color: #2B65FE;
		border-radius: 4rpx;
	}

	.info-item {
		display: flex;
		margin-bottom: 16rpx;
		font-size: 28rpx;
		line-height: 1.6;
	}

	.item-label {
		width: 160rpx;
		color: #666;
		flex-shrink: 0;
	}

	.item-value {
		flex: 1;
		color: #333;
	}

	/* 按钮样式 */
	.action-container {
		padding: 30rpx;
		display: flex;
		justify-content: center;
	}

	.btn {
		padding: 20rpx 40rpx;
		border-radius: 8rpx;
		font-size: 30rpx;
		margin: 0 20rpx;
	}

	.btn-primary {
		background-color: #2B65FE;
		color: #fff;
	}

	/* 评价按钮特别样式 */
	.evaluate-btn {
		width: 80%;
		height: 90rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: bold;
		letter-spacing: 4rpx;
		border-radius: 45rpx;
		box-shadow: 0 4rpx 12rpx rgba(43, 101, 254, 0.3);
		transition: all 0.3s;
	}
	
	.evaluate-btn:active {
		transform: scale(0.97);
		background-color: #2457e0;
	}

	/* 评价样式 */
	.evaluation-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.rating {
		display: flex;
		align-items: center;
	}

	.score-text {
		margin-left: 20rpx;
		color: #faad14;
		font-size: 28rpx;
	}

	.evaluation-content {
		background-color: #f9f9f9;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 16rpx;
		font-size: 28rpx;
		color: #333;
		word-break: break-all;
		white-space: pre-wrap;
	}

	.evaluation-time {
		text-align: right;
		font-size: 24rpx;
		color: #999;
	}

	/* 评价表单样式 */
	.evaluation-form {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 30rpx;
	}

	.form-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.form-title {
		font-size: 32rpx;
		font-weight: bold;
	}

	.close-btn {
		font-size: 40rpx;
		color: #999;
		padding: 10rpx;
	}

	.form-content {
		margin-bottom: 30rpx;
	}

	.evaluation-tips {
		font-size: 26rpx;
		color: #666;
		background-color: #f8f8f8;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.rating-container,
	.comment-container {
		margin-bottom: 30rpx;
	}

	.rating-title,
	.comment-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
	}

	.stars {
		display: flex;
		align-items: center;
	}

	.rating-desc {
		font-size: 24rpx;
		color: #666;
		margin-top: 10rpx;
		text-align: center;
	}

	.comment-input {
		width: 100%;
		height: 200rpx;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}

	.comment-count {
		text-align: right;
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
	}

	.form-footer {
		display: flex;
		justify-content: space-between;
	}

	.btn-cancel {
		background-color: #f5f5f5;
		color: #666;
		flex: 1;
		margin-right: 20rpx;
	}

	.btn-submit {
		background-color: #2B65FE;
		color: #fff;
		flex: 1;
		margin-left: 20rpx;
	}

	.no-content {
		font-size: 26rpx;
		color: #999;
		text-align: center;
		margin: 20rpx 0;
	}
</style>